package cn.com.pg.b2b.pd.truck.appointment.management.service.exception;

import cn.com.pg.b2b.pd.truck.appointment.management.service.common.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;

@Slf4j
@RestControllerAdvice
@Order(1)
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception exception) {
        String message = exception.getMessage();
        log.error("全局异常捕获Exception：{}", message, exception);
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        if (exception instanceof HttpRequestMethodNotSupportedException) {
            code = HttpStatus.METHOD_NOT_ALLOWED.value();
        }
        return ResponseEntity.ok(new ResponseDTO<>(code, message));
    }

    @ExceptionHandler(CommonException.class)
    public ResponseEntity<Object> handleException(CommonException exception) {
        String message = exception.getMessage();
        log.error("全局异常捕获CommonException：{}", message, exception);
        return ResponseEntity.ok(new ResponseDTO<>(exception.getCode(), message));
    }


    @ExceptionHandler(ServletException.class)
    public ResponseEntity<Object> handleException(ServletException exception) {
        String message = exception.getMessage();
        log.error("全局异常捕获AccessDeniedException：{}", message);
        return ResponseEntity.ok(new ResponseDTO<>(500, message));
    }

}
